package ua.races.command.implementation;

import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import ua.races.vo.Horse;
import ua.races.vo.Race;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class PostCoefsCommand implements ServletCommand {
    private static final Logger log = Logger.getLogger(PostCoefsCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        Race race = null;
        RacesDaoImpl dao;
        Long raceId = null;
        Map<Race, Map<Horse, Double>> raceCoefs = null;
        Map<Horse, Double> coefs = null;
        Horse horse = null;
        Double coef = null;
        String[] horseIds = null;
        String[] coefValues = null;
        String redirectUrl = null;
        String message = null;

        try {
            message = "Sorry, you had inputted wrong data " +
                    "and coefficients have not been successfully added (((";
            redirectUrl = req.getHeader("referer");

            dao = (RacesDaoImpl) context.getAttribute("DAO");
            raceId = Long.parseLong(req.getParameter("raceId"));
            race = dao.findRaceById(raceId);
            raceCoefs = new HashMap<Race, Map<Horse, Double>>();
            coefs = new HashMap<Horse, Double>();
            horseIds = req.getParameterValues("horseId");
            coefValues = req.getParameterValues("coef");

            for (int i = 0; i < horseIds.length; i++) {
                horse = dao.findHorseById(Long.parseLong(horseIds[i]));
                coef = Double.parseDouble(coefValues[i]);
                coefs.put(horse, coef);
            }

            raceCoefs.put(race, coefs);
            if (horseIds.length != dao.setCoefs(raceCoefs)) {
                throw new SQLException("wrong input data");
            } else {
                message = "Your coefs has been successfully added";
                redirectUrl = "/prepareBookmaker.do";
                log.info("Coefficients are successfully posted");
            }
        } catch (SQLException e) {
            log.error(e);
        } catch (Throwable e) {
            log.error(e);
        } finally {
            try {
                req.setAttribute("message", message);
                req.setAttribute("URL", redirectUrl);
                context.getRequestDispatcher("/redirection.jsp").forward(req, resp);
            } catch (ServletException e) {
                log.error(e);
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}